package net.flintx.array;

import java.util.Arrays;
import java.util.Collections;

/**
 * Created by flintx on 2018/1/9.
 */
public class RotateArray {

    public int gcd(int a, int b) {
        return b == 0? a: gcd(b, a % b);
    }
    public void rotate(int[] nums, int k) {
        if (nums.length == 0 || k == 0) {
            return;
        }
        k %= nums.length;
        int kAndLenGcd = gcd(k, nums.length);
        for (int i = 0; i < kAndLenGcd; i++) {
            int pos = i, cnt = nums.length / kAndLenGcd, temp1 = nums[pos], temp2;
            while (cnt > 0) {
                pos = (pos + k) % nums.length;
                temp2 = nums[pos];
                nums[pos] = temp1;
                temp1 = temp2;
                cnt--;
            }
        }

    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start++] = nums[end];
            nums[end--] = temp;
        }
    }
    public void betterMethod(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k,nums.length - 1);
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6};
        int k = 2;
//        new RotateArray().rotate(nums, k);
        new RotateArray().betterMethod(nums, k);
        System.out.println(Arrays.toString(nums));
    }
}

//1, 2, 3, 4, 5, 6, 7
//1, 2, 3, 4, 1, 6, 7
//4, 3, 2, 1, 7, 6, 5
//
//4, 5, 6, 7, 1, 2, 3